package org.zlb.netty.server.serial;

import org.zlb.netty.proto.SubReqProto;
import org.zlb.netty.proto.SubReqProto.SubReq;
import org.zlb.netty.proto.SubRespProto;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

public class SubReqProtoServerHandler extends ChannelInboundHandlerAdapter {
    
    private int heartBeat = 0;

    
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        heartBeat = 0;
        
        SubReqProto.SubReq req = (SubReq)msg;
        if (req.getSubReqId() == 0) {
            System.out.println("收到心跳测试包，不处理");
            return;
        }
        System.out.println(req.getSubReqId());
        System.out.println(req.getUserName());
        System.out.println(req.getUserPhone());
        System.out.println(req.getAddress());
        ctx.writeAndFlush(resp(req.getSubReqId()));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    private SubRespProto.SubResp resp(int reqId) {
        SubRespProto.SubResp.Builder builder = SubRespProto.SubResp.newBuilder();
        builder.setSubReqId(reqId);
        builder.setRespCode(0);
        builder.setDesc("订购成功，3日后送达");
        
        return builder.build();
    }
    
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.READER_IDLE) {
                if (heartBeat >= 3) {
                    ctx.disconnect();
                    System.out.println("与远端地址" + ctx.channel().remoteAddress() + "断开连接！");
                } else {
                    heartBeat ++;
                    System.out.println("丢失第" + heartBeat + "个心跳包");
                }
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}
